define(function(require){
	var main =require('/static/main.js');
	require('/static/ajaxfileupload.js');
	var m = new main();
	function Cont(){
		this.Fun._init();
	}
	Cont.prototype.Fun = {
		TagIds:[],
		_init:function(){
		    this.getlist();
		    this.changeHead();
			this.bindEvent();
		},
		bindEvent:function(){
			var _this = this;
			// 点击选择标签
			$(document).on('click','.Label_btnspan',function(){
				// 100 筛选  200 个人详情的 是否选中
				var type = parseInt($('.Label_btn').attr('data-type'));
				// 修改 多选
				// if(type == 100){
				// 	$(this).siblings().removeClass('E8ECEE');
				// 	if($(this).hasClass('E8ECEE')){
				// 		$(this).removeClass('E8ECEE')
				// 	}else{
				// 		$(this).addClass('E8ECEE')
				// 	}
				// }else{
					if($(this).hasClass('E8ECEE')){
	                    $(this).removeClass('E8ECEE')
	                }else{
	                    $(this).addClass('E8ECEE')
	                }
				// }

			})
			$(document).on('click','.chose_li',function(){
				$(this).remove();
				if($('.select2-choices div li').length == 0){
					$('.select2-search-choice').show();
				}
				// $('.Label_btn span').removeClass('E8ECEE');
				// $(this).hide();
				// $(this).attr('data-id','')
				return false;
			})
			// 选择完成
			$('.choseOk').click(function(){
				var type = parseInt($('.Label_btn').attr('data-type'));
				if(type == 100){
					var str = ''
					if($('.Label_btn span').hasClass('E8ECEE')){
		                $('.Label_btnspan.E8ECEE').each(function(k,v){
		                    var id = $(this).data('id')
		                    var name = $(this).data('name')
		                    str +='<li class="chose_li"  data-id="'+id+'">'+name+'<span class="ion-close-round"></span></li>'
		                })
		               	$('.select2-choices div').html(str).show();
						$('.select2-search-choice').hide();
					}else{
						$('.select2-search-choice').show();
						$('.select2-choices div').hide();
					}
				}else{
					var str = ''
	                var TagIds = [];
	                $('.Label_btnspan.E8ECEE').each(function(k,v){
	                    var id = $(this).data('id')
	                    var name = $(this).data('name')
	                    TagIds.push(id);
	                    str +='<li data-id="'+v.id+'">'+name+'</li>'
	                })
	                _this.TagIds = TagIds;
	                $('.edit_sign').html(str+'<div class="edit_gochose" data-toggle="modal" data-target="#custom-width-modal">修改标签</div>');
				}

				$('#custom-width-modal').modal('hide');
			})
			// 点击重置按钮
	        $('#btnRefresh').click(function(){
	        	$('.Source option:eq(0)').attr('selected','selected');
	        	$('.UserWorth option:eq(0)').attr('selected','selected');
	        	$('.Phone').val('');
	        	$('.UserName').val('');
	        	$('.select2-choices div li').remove();
	        	$('.select2-search-choice').show();
	        	$('.Label_btn span').removeClass('E8ECEE');
	        })
	        // 选择 筛选标签
	        $('.Label_screening').click(function(){
	        	$('.Label_btn').attr('data-type',100);
	        	_this.getSign('','chose');
	        })
		},
		getlist:function(){
	        var param = {};
	        var sort = 0;
	        var table = $('#datatable').dataTable({
	        	'ordering':false,
	        	"serverSide": true,
	        	"searching":false,
	        	// 'bLengthChange': false,
	        	ajax: function (data, callback, settings) {
	                //封装请求参数
	                param.PageSize = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
	                param.start = data.start;//开始的记录序号
	                param.PageNo = (data.start / data.length)+1;//当前页码
	        		sort = (param.PageNo-1)*param.PageSize;
	                //ajax请求数据
	                $.ajax({
	                    type: "POST",
	                    url: "/customer/customer-list",
	                    cache: false,  //禁用缓存
	                    data: param,  //传入组装的参数
	                    dataType: "json",
	                    success: function (result) {
                    	    var returnData = {};
                            returnData.draw = data.draw;
                            returnData.recordsTotal = result.total;
                            returnData.recordsFiltered = result.total;
                            returnData.data = result.data;
                            callback(returnData);
	                    }
	                });
	            },
				"aoColumns":[
					{
						"mDataProp": 'UserRemarkName',
						render:function(data){
							sort ++;
                    		return sort;
                    	}
					}, 
					{"mDataProp": 'UserRemarkName',
                        "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            var Name = '';
                            if(oData.UserRemarkName){
                                Name = oData.UserRemarkName;
                            }else{
                                Name = oData.UserName;
                            }
                            $(nTd).html(Name);
                        }
                    },
                    {"mDataProp": 'Phone'},
                    {"mDataProp": 'SexName'},
                    {"mDataProp": 'SourceName'},
                    {"mDataProp": 'UserWorthName'},
                    {
                    	"mDataProp": 'CreateTime',
                    	render:function(data){
                    		if(data){
                    			return m.formatTimeAll2(data)
                    		}else{
                    			return '暂无添加时间';
                    		}
                    	}
                	},
                    {
			            "mDataProp": "CustomerId",
			            "sClass": "option_btn",
			            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
			            	// console.log(arguments);
			                $(nTd).html('<span data-toggle="modal" data-target="#con-close-modal" data-toggle="tooltip" class="btn_detial" data-id="'+sData+'">编辑</span>\
                                            <span class="btn_del"  data-id="'+sData+'">删除</span>');

			            }
			        }
				],
	        }).api();
	        // 点击搜索
	        $('#btnSearch').click(function(){
	        	param.Source = $('.Source option:selected').val();
	        	param.UserWorth = $('.UserWorth option:selected').val();
	        	param.Phone = $('.Phone').val();
	        	param.UserName = $('.UserName').val();

	        	var TagIds = [];
                $('.select2-choices .chose_li').each(function(k,v){
                    var id = $(this).data('id')
                    TagIds.push(id);
                })
	        	param.TagIds = TagIds;
	        	table.ajax.reload();
	        })
	        // 编辑
	        var _this = this;
	        $(document).on('click','.btn_detial',function(){
	        	$('.modal-title').html('客户详情');
	        	$('.Label_btn').attr('data-type',200);
	        	$('.modal-backdrop').css({'z-index':21})
	        	$('#con-close-modal').css('z-index',22)
	        	$('.bg-profileinfo').show();
	        	$('.edit_userinfo').html('修改');

	        	var id = parseInt($(this).attr('data-id'));
	        	$('.edit_userinfo').attr('data-id',id)
	        	_this.getSign(id);
	        	$.ajax({
                    type: "POST",
                    url: "/customer/customer-infodetial",
                    data: {CustomerId:id},  //传入组装的参数
                    dataType: "json",
                    success: function (ret) {
                    	_this.getgroup(ret.GroupId);
                	  	$('.PhoneInfo').val(ret.Phone);
                	  	$('.UserPhoto').attr('src',ret.UserPhoto);
                	  	$('.Email').val(ret.Email);
                	  	$('.UserNameText').html(ret.UserName);
                	  	$('.UserRemarkName').val(ret.UserRemarkName);
                	  	if(ret.Birthday){
                            ret.Birthday = m.format(m.substrTime(ret.Birthday));
                       	}
                       $('.Birthday').val(ret.Birthday);
                       $('#Sex option').each(function(){
                       		if($(this).val() == ret.Sex){
                       			$(this).attr('selected',true);
                       		}else{
                       			$(this).removeAttr('selected');
                       		}
                       })
                       var str = '';
                       $.each(ret.TagInfoList,function(k,v){
                            str += '<li data-id="'+v.TagId+'">'+v.TagName+'</li>';
                        })
                       $('.edit_sign').html(str+'<div class="edit_gochose" data-toggle="modal" data-target="#custom-width-modal">修改标签</div>');
                	   $('.Remark').val(ret.Remark);
                	   $(".Address").val(ret.Address)
                    }
                });
	        })
	        // 点击修改信息 + 添加按钮
	        $('.edit_userinfo').click(function(){
	        	var $this = $(this);
	        	var CustomerId = parseInt($(this).attr('data-id'));
	        	var UserPhoto = $('.UserPhoto').attr('data-src');
	        	var data = {
                    UserRemarkName:$('.UserRemarkName').val(),
                    Phone:$('.PhoneInfo').val(),
                    GroupId:parseInt($('#chose_group option:selected').val()),
                    Sex:parseInt($('#Sex option:selected').val()),
                    Email:$('.Email').val(),
                    Address:$('.Address').val(),
                    Birthday:$('.Birthday').val(),
                    Remark:$('.Remark').val(),
                    TagIds:_this.TagIds, 
                    CustomerId:CustomerId,              
                    UserPhoto:UserPhoto,              
                }
                if($.trim($(this).html()) == '修改'){
                	data.type = 100;
                }else if($.trim($(this).html()) == '添加'){
                	data.type = 200;
                    data.UserName = $('.UserRemarkName').val()
                }
	        	$.ajax({
                    type: "POST",
                    url: "/customer/customer-editinfo",
                    data:data, 
                    dataType: "json",
                    success: function (ret) {
                	  	if(ret.IsBizSuccess){
                	  		if($.trim($this.html()) == '修改'){
                	  			layer.msg('编辑成功');
			                }else if($.trim($this.html()) == '添加'){
			                	layer.msg('添加成功');
			                }
                	  		$('#con-close-modal').modal('hide');
                	  		table.ajax.reload();
                	  	}else{
                	  		layer.msg(ret.ErrMsg);
                	  		return false;
                	  	}
                    }
                });
	        })
	        // 点击添加客户
	        $('#addToTable').click(function(){
	        	$('.Label_btn').attr('data-type',200)
	        	setTimeout(function(){
	        		$('.modal-backdrop').css({'z-index':21})
	        		$('#con-close-modal').css('z-index',22)
	        	},100)
	        	$('.modal-title').html('添加客户');
	        	$('.edit_userinfo').html('添加');
	        	$('.bg-profileinfo').hide();

	        	$('.UserRemarkName').val('')
	        	$('.PhoneInfo').val('').attr('readonly',false)
	        	$('#chose_group option').each(function(){
	        		if(parseInt($(this).val()) == 0){
	        			$(this).attr('selected','selected');
	        		}else{
	        			$(this).removeAttr('selected');
	        		}
	        	})
	        	$('#Sex option').each(function(){
	        		if(parseInt($(this).val()) == -1){
	        			$(this).attr('selected','selected');
	        		}else{
	        			$(this).removeAttr('selected');
	        		}
	        	})
	        	$('.Email').val('')
	        	$('.Address').val('')
	        	$('.Birthday').val('')
	        	$('.Remark').val('')
	        	$('.edit_sign').html('<div class="edit_gochose" data-toggle="modal" data-target="#custom-width-modal">选择标签</div>');
	        	$('.Label_btn span').removeClass('E8ECEE');
	        	_this.getSign('');
	        	_this.getgroup(0);
	        })
	        // 点击删除
	        $(document).on('click','.btn_del',function(){
	        	var id = parseInt($(this).attr('data-id'));
	        	layer.confirm('是否删除客户信息？', {
				  btn: ['确定','取消'] //按钮
				}, function(){
				  	$.ajax({
	                    type: "POST",
	                    url: "/customer/customer-delinfo",
	                    data:{CustomerIds:[id],type:200}, 
	                    dataType: "json",
	                    success: function (ret) {
	                	  	if(ret.IsBizSuccess){
				                layer.msg('删除成功');
	                	  		table.ajax.reload();
	                	  	}else{
	                	  		layer.msg(ret.ErrMsg);
	                	  		return false;
	                	  	}
	                    }
	                });
				});
	        	
	        })

	        // 添加标签
	        $(document).on('click','.Label_btnadd',function(){
				var index = layer.prompt({
				       title : '标签名称：'
				},function(val, index){
					  if(val.length > 10){
					  	layer.msg('标签名称不能大于10个字');
					  	layer.close(index);
					  	return false;
					  }else{
					      var data = {
					      	TagName:val,
					      }
					      $.ajax({
	                		type: "POST",
							url:'/customer/sign-add',
							data:data,
							dataType: "json",
							success:function (ret) {
				               if(ret.IsBizSuccess){
				               		layer.msg('添加成功');
				               		_this.getSign();
					     			layer.close(index);
				               }else{
				               		layer.msg('添加失败');
					     			layer.close(index);
				               }
				            }
			        	 })
					  }
				});
			})
		},
		getSign:function(CustomerId,chose){
			$.ajax({
                type: "POST",
                url: "/customer/sign-list",
                data:{CustomerId:CustomerId},
                dataType: "json",
                success: function (ret) {
            	   var str = '';
            	   if(ret.Models.length > 0){
            	   		if(CustomerId){
            	   			var classname = '';
	            	   		$.each(ret.Models,function(k,v){
	            	   			classname = v.IsChoose ? 'E8ECEE':'';
		            	   		str+='<span class="Label_btnspan '+classname+'" data-id="'+v.TagId+'" data-name="'+v.TagName+'">'+v.TagName+'</span>'
		            	    })
            	   		}else{
            	   			$.each(ret.Models,function(k,v){
		            	   		str+='<span class="Label_btnspan" data-id="'+v.TagId+'" data-name="'+v.TagName+'">'+v.TagName+'</span>'
		            	    })
            	   		}
            	   		if(!chose){
	            	    	str+='<span class="Label_btnadd" data-dismiss="modal">添加标签</span>'
            	   		}
            	   }else{
            	   		if(chose){
            	   			$('.Label_btn').css({'text-align':'center'})
            	   			str+='暂无标签'
            	   		}
            	   }
            	   	   $('.Label_btn').html(str);
                }
            });
		},
		getgroup:function(id){
            var _this = this;
            $.ajax({
                type: "POST",
                url: "/customer/group-list",
                dataType: "json",
                success: function (ret) {
                    var str = '',selected = '';
                    str += '<option value="0" selected="selected">请选择分组</option>';
                    ret.Models.forEach(function(v,k){
                        if(parseInt(id) != 0){
                            selected = id == v.GroupId ? 'selected' : '';
                        }
                        str += '<option value="'+v.GroupId+'" '+selected+'>'+v.GroupName+'</option>'
                    })
                    $('#chose_group').html(str);
                }
            });
        },
        changeHead:function(){
            var _this = this;
            //图片上传
            $("#file").on("change",function () {
                ajaxFileUpload();
            });
            function ajaxFileUpload(){
                console.log(1);
                $.ajaxFileUpload({
                    url:m.baseUrl+"/customer/edit-head",
                    secureuri: false,
                    fileElementId: 'file',
                    dataType: 'json',
                    success: function (ret) {
                        if(ret.IsBizSuccess){
                            $(".UserPhoto").attr({"src":ret.Photo,'data-src':ret.FileName})
                        }else{
                        	layer.msg(ret.ErrMsg);
                            return false;
                        }
                    }
                })
                return false;
            }
        },



	}
	var a = new Cont();

})